package com.CST.config;

import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * <p></p>
 *
 * @author: ly
 * @date: 2021/05/05 10:22
 **/
@Configuration
@MapperScan(value = "com.CST.mapper.cst", sqlSessionFactoryRef = "cstSqlSessionFactory")
public class DefaultDataSourceConfig1 {

    @Autowired
    private MybatisPlusInterceptor mybatisPlusInterceptor;

    @Autowired
    private MyMetaObjectHandler myMetaObjectHandler;

    @Bean(name = "cstDataSource")
    @Primary
    @ConfigurationProperties(prefix = "spring.datasource.cst")
    public DataSource getDateSource() {
        return DataSourceBuilder.create()
                .build();
    }

    @Bean(name = "cstSqlSessionFactory")
    @Primary
    public SqlSessionFactory cstSqlSessionFactory(@Qualifier("cstDataSource") DataSource dataSource) throws Exception {

        //SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setLogImpl(org.apache.ibatis.logging.stdout.StdOutImpl.class);
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setMetaObjectHandler(myMetaObjectHandler);
        bean.setDataSource(dataSource);
        bean.setConfiguration(configuration);
        bean.setGlobalConfig(globalConfig);
        bean.setPlugins(mybatisPlusInterceptor);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/cst/*.xml"));
        return bean.getObject();
    }

    @Bean(name = "cstSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate cstSqlSessionTemplate(@Qualifier("cstSqlSessionFactory") SqlSessionFactory sessionFactory) {
        return new SqlSessionTemplate(sessionFactory);
    }

//    @Bean
//    public OracleKeyGenerator oracleKeyGenerator() {
//        return new OracleKeyGenerator();
//    }
}
